﻿using yao.Entity;
using yao.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Titan;

namespace yao.website.Controllers
{
    /// <summary>
    /// 客户管理
    /// </summary>
    public class CustomerController : BaseController
    {
        public ActionResult Index(int? p)
        {
            int pageIndex = p == null ? 1 : (int)p;
            ViewBag.PageIndex = pageIndex;

            //为提高性能，需要时才打开数据库，后面还会有一次数据库验证 
            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(Customer);
                q.Selects.Add(Customer_.CustomerId);//唯一Id
                q.Selects.Add(Customer_.CustomerNo);//客户编号
                q.Selects.Add(Customer_.CompanyCode);//企业代码
                q.Selects.Add(Customer_.CustomerName);//客户名称
                q.Selects.Add(Customer_.ContactName);//联系人
                q.Selects.Add(Customer_.Address);//地址
                q.Selects.Add(Customer_.CustomerLevel.CustomerLevelName);//客户等级
                q.Selects.Add(Customer_.ReceivableCapital);//应收款
                q.Selects.Add(Customer_.NotCompletedOrderCount);//未完成订单数量

                q.Selects.Add(Customer_.LatestOrderTime);//最近订货时间
                q.Selects.Add(Customer_.Employee.EmployeeName);//负责人
                q.Selects.Add(Customer_.IsActive);//启用状态
                q.Wheres.Add(Customer_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                q.PageSize = 20;
                q.PageIndex = pageIndex;
                q.ReturnMatchedCount = true;
                Customers customers = new Customers();
                customers.TotalCount = cn.SelectCollection(customers.Items, q);
                return View(customers);                
            }
        }

        public ActionResult Edit(long? id)
        {
            Customer customer = new Customer();
            if (id != null)
            {
                ViewBag.Title = "修改客户-" + id;
                customer.CustomerId = (long)id;
                using (IDbSession cn = OpenSession())
                {
                    cn.Select(customer, Customer_.ALL, Customer_.Employee.EmployeeName, Customer_.CustomerLevel.CustomerLevelName);
                }
            }
            else
            {
                QueryExpression query = new QueryExpression();
                query.EntityType = typeof(CustomerLevel);
                query.Selects.Add(CustomerLevel_.CustomerLevelId);
                query.Selects.Add(CustomerLevel_.CustomerLevelName);
                query.Wheres.Add(CustomerLevel_.Turn.TEqual(0));
                query.Wheres.Add(CustomerLevel_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                CustomerLevels customerLevels = new CustomerLevels();
                using (IDbSession cn = OpenSession())
                {
                    cn.SelectCollection(customerLevels.Items, query);
                }
                customer.CustomerLevelId = 0;
                if (customerLevels.Items.Count > 0) {
                    customer.CustomerLevel = customerLevels.Items[0];
                    customer.CustomerLevelId = customerLevels.Items[0].CustomerLevelId;
                }
                customer.AreaId = CurrentEmployee.AreaId; //需要加载默认的areaId
            }

            return View(customer);
        }
        [HttpPost]
        public ActionResult Edit(long? id, Customer customer)
        {
            #region 验证
            Validate(customer, Customer_.CustomerNo);
            Validate(customer, Customer_.CustomerName);
            Validate(customer, Customer_.FullName);
            Validate(customer, Customer_.ContactName);
            //Validate(customer, Customer_.Phone);
            Validate(customer, Customer_.Mb);
            Validate(customer, Customer_.Email);
            Validate(customer, Customer_.Address);
            if (customer.CustomerLevelId < 1 || customer.CustomerLevelId > 3)
            {
                AddFormError(Customer_.CustomerLevelId, "客户等级无效");
            }
            if (!ApplicationCache.IsValidAreaId(customer.AreaId))
            {
                AddFormError(Customer_.AreaId, "所属地区无效");
            }
            #endregion


            if (!IsValid) return View(customer);

            //为提高性能，需要时才打开数据库，后面还会有一次数据库验证

            using (IDbSession cn = OpenSession())
            {
                if (id == null)//添加
                {
                    customer.CompanyId = CurrentEmployee.CompanyId;//必须先赋值才能后续验证

                    #region validate
                    ConditionExpressionCollection cs = new ConditionExpressionCollection();
                    cs.Add(Customer_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                    cs.Add(Customer_.CustomerNo.TEqual(customer.CustomerNo));
                    if (cn.Exists<Customer>(cs))
                    {
                        AddFormError(Customer_.CustomerNo, "客户编号不允许重复");
                    }
                    if (!IsValid) return View(customer);

                    cs = new ConditionExpressionCollection();
                    cs.Add(Customer_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                    cs.Add(Customer_.CustomerName.TEqual(customer.CustomerName));
                    if (cn.Exists<Customer>(cs))
                    {
                        AddFormError(Customer_.CustomerName, "客户名称不允许重复");
                    }
                    if (!IsValid) return View(customer);
                    #endregion
                    
                    customer.GlobalCompanyId = 0;
                    customer.IsActive = true;
                    customer.ReceivableCapital = 0;
                    customer.CreateTime = DateTime.Now;
                    customer.EmployeeId = CurrentEmployee.EmployeeId;
                    cn.Insert(customer);
                }
                else
                {
                    customer.CustomerId = id.Value;

                    #region validate
                    ConditionExpressionCollection cs = new ConditionExpressionCollection();
                    cs.Add(Customer_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                    cs.Add(Customer_.CustomerNo.TEqual(customer.CustomerNo));
                    cs.Add(Customer_.CustomerId.TNotEqual(customer.CustomerId));
                    if (cn.Exists<Customer>(cs))
                    {
                        AddFormError(Customer_.CustomerNo, "客户编号不允许重复");
                    }
                    if (!IsValid) return View(customer);

                    cs = new ConditionExpressionCollection();
                    cs.Add(Customer_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                    cs.Add(Customer_.CustomerName.TEqual(customer.CustomerName));
                    cs.Add(Customer_.CustomerId.TNotEqual(customer.CustomerId));
                    if (cn.Exists<Customer>(cs))
                    {
                        AddFormError(Customer_.CustomerName, "客户名称不允许重复");
                    }
                    if (!IsValid) return View(customer);
                    #endregion

                    customer.UpdateTime = DateTime.Now;
                    cn.Update(customer, Customer_.AreaId, Customer_.ContactName, Customer_.CustomerLevelId, Customer_.UpdateTime,
                        Customer_.CustomerName, Customer_.CustomerNo, Customer_.Email, Customer_.FullName,
                        Customer_.GlobalCompanyId, Customer_.Mb, Customer_.Phone, Customer_.Remark,Customer_.EmployeeId,Customer_.Address,Customer_.X,Customer_.Y, Customer_.IsMapped, Customer_.CompanyTypeId);
                }
            }
            return new IframeResult(Url.Action("Edit"),Url.Action("Index"));
        }

        #region update改为跟insert统一方法，以下注释掉
        //public ActionResult Update(long customerId)
        //{
        //    Customer customer = new Customer();
        //    customer.CustomerId = customerId;
        //    using (IDbSession cn = OpenSession())
        //    {
        //        cn.Select(customer);
        //    } 
        //    return View(customer);
        //}
        //[HttpPost]
        //public ActionResult Update(Customer customer)
        //{
        //    #region 验证
        //    Validate(customer, Customer_.CustomerNo);
        //    Validate(customer, Customer_.CustomerName);
        //    Validate(customer, Customer_.FullName);
        //    Validate(customer, Customer_.ContactName);
        //    Validate(customer, Customer_.Phone);
        //    Validate(customer, Customer_.Mb);
        //    Validate(customer, Customer_.Email);
        //    Validate(customer, Customer_.Address);
        //    if (customer.CustomerLevelId < 1 || customer.CustomerLevelId > 3)
        //    {
        //        AddFormError(Customer_.CustomerLevelId, "客户等级无效");
        //    }
        //    if (!ApplicationCache.IsValidAreaId(customer.AreaId))
        //    {
        //        AddFormError(Customer_.AreaId, "所属地区无效");
        //    }
        //    #endregion


        //    if (!IsValid) return View();

        //    //为提高性能，需要时才打开数据库，后面还会有一次数据库验证

        //    using (IDbSession cn = OpenSession())
        //    {

        //        customer.CompanyId = CurrentEmployee.CompanyId;//必须先赋值才能后续验证

        //        #region validate
        //        ConditionExpressionCollection cs = new ConditionExpressionCollection();
        //        cs.Add(Customer_.CompanyId.TEqual(CurrentEmployee.CompanyId));
        //        cs.Add(Customer_.CustomerNo.TEqual(customer.CustomerNo));
        //        cs.Add(Customer_.CustomerId.TNotEqual(customer.CustomerId));
        //        if (cn.Exists<Customer>(cs))
        //        {
        //            AddFormError(Customer_.CustomerNo, "客户编号不允许重复");
        //        }
        //        if (!IsValid) return View();

        //        cs = new ConditionExpressionCollection();
        //        cs.Add(Customer_.CompanyId.TEqual(CurrentEmployee.CompanyId));
        //        cs.Add(Customer_.CustomerName.TEqual(customer.CustomerNo));
        //        cs.Add(Customer_.CustomerId.TNotEqual(customer.CustomerId));
        //        if (cn.Exists<Customer>(cs))
        //        {
        //            AddFormError(Customer_.CustomerNo, "客户名称不允许重复");
        //        }
        //        if (!IsValid) return View();
        //        #endregion

        //        customer.GlobalCompanyId = 0;
        //        customer.IsActive = true;
        //        customer.ReceivableCapital = 0;
        //        customer.CreateTime = DateTime.Now;
        //        customer.EmployeeId = CurrentEmployee.EmployeeId;
        //        cn.Update(customer,Customer_.AreaId,Customer_.ContactName,Customer_.CustomerLevelId,
        //            Customer_.CustomerName, Customer_.CustomerNo, Customer_.Email, Customer_.FullName,
        //            Customer_.GlobalCompanyId, Customer_.Mb, Customer_.Phone, Customer_.Remark);
        //    }
        //    return null;
        //}
        #endregion

        [HttpPost]
        public ActionResult Delete(long customerId)
        {
            Customer customer = new Customer();
            customer.CustomerId = customerId;
            bool ret = false;
            //为提高性能，需要时才打开数据库，后面还会有一次数据库验证 
            using (IDbSession cn = OpenSession())
            { 
              ret= cn.Delete(customer)>0;
            }
            return Json(new { ret = ret });
        }

        [HttpPost]
        public ActionResult Active(long customerId,bool isActive)
        {
            Customer customer = new Customer {
                CustomerId = customerId,
                IsActive=isActive
            };
            bool ret = false;
            //为提高性能，需要时才打开数据库，后面还会有一次数据库验证 
            using (IDbSession cn = OpenSession())
            {
                ret = cn.Update(customer,Customer_.IsActive) > 0;
            }
            return Json(new { ret = ret });
        }


        public ActionResult Detail(long id)
        {
            using (IDbSession cn = OpenSession())
            {
                Customer customer = new Customer { CustomerId = id };
                cn.Select(customer, Customer_.ALL,Customer_.CustomerLevel.CustomerLevelName,Customer_.Employee.EmployeeName);
                return View(customer);
            }
        }

        public ActionResult MapAddress() {
            return View();
        }

    }
}
